package com.moli.iov.admin.mq.activemq;


import com.moli.iov.admin.model.dto.WebSocketDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ScheduledMessage;
import org.apache.activemq.command.ActiveMQTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

/**
 * <p>
 * ActiveMQ 生产者
 * </p>
 *
 * @Auther: lws
 * @Date: 2018/11/28 15:23
 */
@Component
@Slf4j
public class ActiveMQProducer {

    @Autowired
    private JmsTemplate jmsTemplate;

    @Resource
    private ActiveMQTopic delayTopic;



    /**
     * 延时时间
     */
    @Value("${general.delay.time}")
    private Long generalDelayTime;

    /**
     * 推送
     *
     * @param webSocketDto
     */
    @Async
    public void send(WebSocketDto webSocketDto) {
//        taskExecutor.execute(() -> {
            log.debug("ActiveMQ 发送延时消息开始，入参：{}", webSocketDto);
            jmsTemplate.send(delayTopic, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    ObjectMessage objectMessage = session.createObjectMessage(webSocketDto);
                    objectMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, webSocketDto.getTimer());
                    log.debug("已发送延时消息 queue: {}, 延时时间：{}, 消息：{}", delayTopic, generalDelayTime, webSocketDto);
                    return objectMessage;
                }
            });
            log.debug("ActiveMQ 发送延时消息完成，入参：{}", webSocketDto);

//        });

    }
}
